package com.hbnu.zhanglian.client.network;

import java.io.*;
import java.net.Socket;

public class GameConnection {
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;

    public boolean connect(String host, int port) {
        try {
            socket = new Socket(host, port);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    public void startMessageListening(MessageHandler handler) {
        new Thread(() -> {
            try {
                String message;
                while ((message = in.readLine()) != null) {
                    handler.handleMessage(message);
                }
            } catch (IOException e) {
                // 连接断开
            }
        }).start();
    }

    public void sendMessage(String message) {
        if (out != null) {
            out.println(message);
        }
    }

    public void disconnect() {
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {}
    }

    public interface MessageHandler {
        void handleMessage(String message);
    }
}